# python3.6

import random

from paho.mqtt import client as mqtt_client


# broker = 'broker.emqx.io'
# port = 1883
# topic = "/python/mqtt"
# # generate client ID with pub prefix randomly
# client_id = f'python-mqtt-{random.randint(0, 100)}'
broker = 'yigrow.cn'
port = 5872
username = 'shhooserver001'
passwd = 'shhoo2018'

broker = '127.0.0.1'
port = 9999
username = ''
passwd = ''

topic = "topicbase/413e63f7e0dd5381fdbb324bf048068ab206dd06ea8885c7a71f137832dfd9a8/test"
# generate client ID with pub prefix randomly
client_id = f'python-mqtt-{random.randint(0, 1000)}'

def connect_mqtt() -> mqtt_client:
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)

    client = mqtt_client.Client(client_id)
    client.on_connect = on_connect
    # 连接mqtt服务器
    client.username_pw_set(username, password=passwd)
    # client.connect(broker, port)
    client.subscribe(topic)
    def on_message(client, userdata, msg):
        print(msg)
    client.on_message = on_message
    client.connect(broker, port)
    return client


def subscribe(client: mqtt_client):
    print('...')
    # def on_message(client, userdata, msg):
    #     print(msg)
    #     # print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")

    # client.subscribe(topic)
    # client.on_message = on_message


def run():
    client = connect_mqtt()
    subscribe(client)
    client.loop_forever()
    

if __name__ == '__main__':
    run()